<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/7/13
 * Time: 11:14
 */
namespace app\repository\wechat;
class Template{
    private $appid;
    private $appsecret;
    private $access_token;
    public function __construct()
    {
        $value = db('wx_config')->where([ 'key' => 'SHOPWCHAT'])->value('value');
        $value = json_decode($value);
        $this->appid = $value->appid;
        $this->appsecret = $value->appsecret;

        //获取并更新access_token
        $acc = db('wx_config')->where('key','ACCESS')->find();
        if(time() - $acc['create_time'] <= 7100){
            $this->access_token = $acc['value'];
        }else{
            $this->access();
        }

    }

    /**
     * 发送模板消息
     * @param $data
     * @return mixed
     */
    public function send($data){
        $res = httpRequest('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->access_token,'POST',$data);
        return json_decode($res,true);
    }

    /**
     * 获取模板id
     * @param $num
     * @return mixed
     */
    public function templateId($num)
    {
        $res = httpRequest('https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token='.$this->access_token,'POST',['template_id_short'=>$num]);
        return json_decode($res,true);
    }
    
    /**
     * 获取access_token
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function access(){
        $t = httpRequest('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret,'GET');
        $t = json_decode($t);
        $this->access_token = $t->access_token;
        return db('wx_config')->where('key','ACCESS')->update(['create_time'=>time(),'value'=>$t->access_token]);
    }
}